import pygame
from constants import * 
class Snake:
    def __init__(self, x, y):
        self.positions = [(x +  i ,y  ) for i in range(1,-2,-1)] 
        self.direction = DOWN
        self.length = 1
    
    def __len__(self):
        return len(self.positions)

    def __getitem__(self,index) :
        return self.positions[index]
    
    def __str__(self) -> str:
        return str(self.positions)

    def turn(self,action):
        if self.direction != UP and action == DOWN :
            self.direction=action
        elif self.direction != LEFT and action == RIGHT :
            self.direction=action
        elif self.direction != RIGHT and action ==LEFT :
            self.direction=action
        elif self.direction != DOWN and action == UP :
            self.direction=action

    def move(self, action , map):
        self.turn(action) 
        x, y = self.positions[0]  # 取出蛇头
        if self.direction == UP :
            x -= 1
        elif self.direction == DOWN :
            x += 1
        elif self.direction == LEFT:
            y -= 1
        elif self.direction == RIGHT:
            y += 1
        
        die = (
            (x,y) in self.positions
            or x < 0 
            or x >= map.height
            or y < 0 
            or y >= map.width
            or map.is_obstacle((x, y))
        )
        return die , x, y

